package com.buyantech.smweb.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */

public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String filePath = "";//存放上传文件的目录
	private String tempFilePath = "";//存放临时文件的目录       

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);
		filePath = config.getInitParameter("filePath");
		System.out.println("filePath1 " + filePath);
		tempFilePath = config.getInitParameter("tempFilePath");
		System.out.println("tempFilePath1 " + tempFilePath);
		filePath = this.getServletContext().getRealPath(filePath);
		System.out.println("filePath2 " + filePath);
		tempFilePath = this.getServletContext().getRealPath(tempFilePath);
		System.out.println("tempFilePath2 " + tempFilePath);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");
		//向客户端发送响应正文
		PrintWriter outNet = response.getWriter();
		String utype = "";
		String uploadFilename = "";
		String error = "";
		String msg = "";
		try {
			//创建一个基于硬盘的FileItem工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//设置向硬盘写数据时所用的缓冲区的大小，此处为4K
			factory.setSizeThreshold(4 * 1024);
			//设置临时目录
			factory.setRepository(new File(tempFilePath));

			//创建一个文件上传处理器
			ServletFileUpload upload = new ServletFileUpload(factory);
			//设置允许上传的文件的最大尺寸，此处为4M
			upload.setSizeMax(4 * 1024 * 1024);

			List items = upload.parseRequest(request);

			Iterator iter = items.iterator();

			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					//					if("type".equals(item.getFieldName())){
					//						utype = item.getString();
					//					}
					//					processFormField(item, outNet); //处理普通的表单域
				} else {
					//					processUploadedFile(item, outNet); //处理上传文件
					uploadFilename = processUploadedFile(item);
				}
			}
			if (!"".equals(uploadFilename)) {
				//				if(utype.equals("contact")) {
				//ExcelRead.Read("E:\\java\\data\\files\\test.xls","1");
				msg = uploadFilename;
				//					outNet.println("file upload success.");
				//					outNet.println("fileName:"+uploadFilename);
				//				}
			} else {
				error = "error";
				msg = "上传失败";
			}

			outNet.print("{");
			outNet.print("\"error\":\"" + error + "\",");
			outNet.print("\"msg\":\"" + msg + "\"");
			outNet.print("}");

			outNet.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void processFormField(FileItem item, PrintWriter outNet) {
		String name = item.getFieldName();
		String value = item.getString();
		outNet.println(name + ":" + value + "\r\n");
	}

	private void processUploadedFile(FileItem item, PrintWriter outNet) throws Exception {
		String filename = item.getName();
		int index = filename.lastIndexOf("\\");
		filename = filename.substring(index + 1, filename.length());
		long fileSize = item.getSize();

		if (filename.equals("") && fileSize == 0)
			return;

		File uploadFile = new File(filePath + "/" + filename);
		item.write(uploadFile);
		outNet.println(filename + "is saved.");
		outNet.println("The size of " + filename + " is " + fileSize + "\r\n");
	}

	private String processUploadedFile(FileItem item) throws Exception {
		String filename = item.getName();
		int index = filename.lastIndexOf("\\");
		filename = filename.substring(index + 1, filename.length());

		//重命名
		String extName = filename.substring(filename.lastIndexOf(".") + 1);
		UUID uuid = UUID.randomUUID();
		String newFilename = uuid.toString() + "." + extName;

		long fileSize = item.getSize();

		if (filename.equals("") && fileSize == 0)
			return "";

		File uploadFile = new File(filePath + "/" + newFilename);
		item.write(uploadFile);
		return newFilename;
	}
}
